package com.seepln.factory;
/**
 * Created by
 *
 * @auth: liqy
 * on 2021/3/3 19:40.
 * desc:
 */

import com.alibaba.fastjson.JSON;
import com.seepln.modal.DBProtocol;
import com.seepln.modal.Protocol;
import org.seepln.connect.Connection;
import org.seepln.connect.RequestDataObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: ConnectFactory
 * @Description:
 *      通讯协议连接工厂类
 * @Author: liqy
 * @CreateDate: 2021/3/3 19:40
 * @UpdateUser: liqy
 * @UpdateDate: 2021/3/3  19:40
 * @UpdateRemark: update TODO
 * @Version: 1.0
 */
public class ConnectFactory {

    private static final Logger log = LoggerFactory.getLogger(ConnectFactory.class);

    private static Map<String, Connection> connectionMap = new ConcurrentHashMap<>(16);

    public Connection build(Protocol protocol) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("build connect: {}", protocol);
        }
        // 以协议name作为通信协议的标识
        if (Objects.nonNull(connectionMap.get(protocol.getName()))) {
            return connectionMap.get(protocol.getName());
        }
        try {
            Connection connection = (Connection) Class.forName(protocol.getClassPath()).getConstructor(Protocol.class).newInstance(protocol);
            connectionMap.put(protocol.getName(), connection);
            return connection;
        } catch (Exception e) {
            log.error("Instant protocol: {} encounter an exception: {} \ncause by {}", protocol.getType(), e.getMessage(), e.getCause());
            throw e;
        }
    }

    public static void main(String[] args) throws Exception {
        ConnectFactory connectFactory = new ConnectFactory();
        /**
         2,
         'fetchdata_conn',
         'com.proinnova.exchange.route.connect.db.DBConnection',
         'db',
         {"url": "jdbc:mysql://139.196.139.82:3306/semir?serverTimezone=UTC&rewriteBatchedStatements=true&characterEncoding=gbk",
         "name": "fetchdataConnector",
         "pass": "!Oz6G%@zn",
         "type": "db",
         "user": "puser",
         "driver": "com.mysql.cj.jdbc.Driver",
         "maxWait": 60000,
         "minIdle": 3,
         "maxActive": 10,
         "initialSize": 5}
         */
        DBProtocol dbProtocol = DBProtocol.builder()
                .type("mysql")
                .version("8.0.23")
                .autoCommit(true)
                .connectionTestQuery("SELECT 1")
                .driver("com.mysql.cj.jdbc.Driver")
                .url("jdbc:mysql://139.196.139.82:3306/semir?serverTimezone=UTC&rewriteBatchedStatements=true&characterEncoding=gbk")
                .connectionTimeout(3)
                .IdleTimeout(6000L)
                .isolateInternalQueries(true)
                .maximumPoolSize(10)
                .maxLifetime(180000L)
                .minimumIdle(5)
                .name("fetchdataConnector")
                .pass("!Oz6G%@zn")
                .user("puser")
                .build();

        Protocol protocol = new Protocol();
        protocol.setClassPath("com.seepln.connect.impl.DBConnector");
        protocol.setType("db");
        protocol.setName("DBConnector");
        protocol.setConfig(JSON.toJSONString(dbProtocol));
        Connection connection = connectFactory.build(protocol);

        /**
         {"sql": "SELECT info.journal_id, info.journal_no, info.journal_type, info.journal_name, info.approve_status, info.post_status,info.journal_date, info.approve_date, info.post_date,info.journal_export_status, info.journal_id_copy,info.lot_no,dtl.line_id,dtl.entity, dtl.account, dtl.detail_param1,dtl.detail_param2, dtl.detail_param3,dtl.debit, dtl.credit,dtl.info_param2, dtl.debit_t, dtl.credit_t FROM app1_journal_info info left join app1_journal_detail dtl on info.journal_id = dtl.journal_id where info.journal_export_status =1 limit 10", "type": "query", "params": null}
         */
        System.out.println(connection.call(RequestDataObject.builder()
                .requestMessage(null)
                .requestParams(new HashMap<String, Object>() {{
                    put("sql", "SELECT info.journal_id, info.journal_no, info.journal_type, info.journal_name, info.approve_status, info.post_status,info.journal_date, info.approve_date, info.post_date,info.journal_export_status, info.journal_id_copy,info.lot_no,dtl.line_id,dtl.entity, dtl.account, dtl.detail_param1,dtl.detail_param2, dtl.detail_param3,dtl.debit, dtl.credit,dtl.info_param2, dtl.debit_t, dtl.credit_t FROM app1_journal_info info left join app1_journal_detail dtl on info.journal_id = dtl.journal_id where info.journal_export_status =1 limit 10");
                    put("type", "query");
                    put("action", "FetchDataAction");
                }})
                .build()));
    }
}
